<template>
  <el-dialog v-loading.fullscreen.lock="fullscreenLoading" ref="ImgsDialog" :before-close="crossSign" title="批量工单"
    :visible.sync="dialog_visible" width="70%" :close-on-click-modal="false" center>
    <div v-for="(item, i) in batchPicturesArrTow" :key="i">
      <div id="geth" class="batch">
        <!-- 图片 -->
        <div style="width: 100%;margin-right: 15px;">
          <img :id="'img'+i" :src="item.imgUrl" style="width: 100%;margin-top: 40px;" />
          <el-button class="fill-btn" @click="editMultiGraph(i)">编辑图片</el-button>
        </div>
        <!-- 表单 -->
        <div style="width: 100%">
          <el-form ref="item" :rules="rules" :model="item" label-position="right" label-width="85px">
            <el-form-item label="所属网点:">
              <el-input v-model="item.pointName" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="评检项:" prop="workorder_type">
              <el-select v-model="item.workorder_type" filterable reserve-keyword placeholder="工单类型" style="width: 100%"
                clearable>
                <el-option-group v-for="group in list_workorder" :key="group.id" :label="group.name">
                  <el-option v-for="item in group.items" :key="item.id" :label="item.name" :value="item.id" />
                </el-option-group>
              </el-select>
            </el-form-item>
            <el-form-item label="优先级:" prop="priority">
              <el-select v-model="item.priority" filterable reserve-keyword placeholder="优先级" style="width: 100%"
                clearable>
                <el-option v-for="item in list_priority" :key="item.id" :label="item.label" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="处理时限:" prop="dealWithTime">
              <el-date-picker
              :default-value="new Date()"
              style="width: 100%"
              v-model="item.dealWithTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions0"
              @change="handle(i)" />
            </el-form-item>
            <el-form-item label="指派给:" prop="dealWithUserId">
              <el-select v-model="item.dealWithUserId" filterable reserve-keyword placeholder="指派给" style="width: 100%"
                clearable>
                <el-option v-for="item in list_user" :key="item.id" :label="item.realName" :value="item.userId" />
              </el-select>
            </el-form-item>
            <el-form-item label="抄送至:" prop="copyUserId">
              <el-select v-model="item.copyUserId" filterable reserve-keyword placeholder="抄送至" style="width: 100%"
                clearable>
                <el-option v-for="item in list_user" :key="item.id" :label="item.realName" :value="item.userId" />
              </el-select>
            </el-form-item>
            <el-form-item label="备注:">
              <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 5}" placeholder="请输入备注" ref="wk_form_remark"
                key="remark" v-model="item.remark" name="remark"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- 分隔线 -->
      <div class="separationLine"></div>
    </div>
    <!-- 按钮 -->
    <div class="buttom">
      <el-button class="plain-btn" @click="close">取消</el-button>
      <el-button class="fill-btn" @click="submit">提交</el-button>
    </div>
    <!-- 编辑用的画布 -->
    <el-dialog @open="innerVisibleshow" width="65%" title="编辑图片" :visible.sync="innerVisible" append-to-body>
      <div id="getw">
        <canvas id="myCanvas"></canvas>
      </div>
      <el-button class="fill-btn" @click="confirmEdit">确定</el-button>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import AddrBranch from "@/components/Address/AddrBranchSelectRegister.vue"
  import {
    workorderAdd,
    uploadWkImg
  } from '@/api/workorder'
  import Atrament from 'atrament'
  export default {
    props: [
      // base64图片数组
      'batchPicturesArr'
    ],
    components: {
      AddrBranch
    },
    data() {
      return {
        // 加载的遮蔽
        fullscreenLoading: false,
        // 打开是否
        dialog_visible: false,
        innerVisible: false,
        // 传来的数组下标
        cache: '',
        // 缓存编辑后的图片
        afterEditing: '',
        // 时限限制
        pickerOptions0: {
          disabledDate:(time)=> {
            return time.getTime() < Date.now()-1 * 24 * 3600 * 1000
          }
        },
        // 工单类型
        list_workorder: [],
        // 优先级
        list_priority: [{
          id: 1,
          label: '高(1天)'
        }, {
          id: 2,
          label: '中(2天)'
        }, {
          id: 3,
          label: '低(7天)'
        }],
        // 处理指派人员
        list_user: '',
        // 拷贝传的数组
        batchPicturesArrTow: [],
        // 多表单校验
        rules: {
          workorder_type: [{
            required: true,
            trigger: "change",
            message: "请选择评检项",
          }, ],
          priority: [{
            required: true,
            trigger: "change",
            message: "请选择优先级",
          }, ],
          dealWithTime: [{
            required: true,
            trigger: "change",
            message: "请选择时限",
          }, ],
          dealWithUserId: [{
            required: true,
            trigger: "change",
            message: "请选择指派人",
          }, ],
          copyUserId: [{
            required: true,
            trigger: "change",
            message: "请选择抄送人",
          }, ]
        }
      }
    },
    methods: {
      // 时间精确到当前以前
      handle (i) {
        var startAt = new Date(this.batchPicturesArrTow[i].dealWithTime) * 1000 /1000
        if(startAt < Date.now()) {
          this.$notify({
            title: "警告",
            message: '选择此刻后的时间会导致工单预期',
            type: 'warning',
            duration: 4000
          })
        }
      },
      // 打开
      open() {
        this.batchPicturesArrTow = this.batchPicturesArr
        this.list_workorder = this.$store.getters.list_workorder || []
        this.list_user = this.$store.getters.list_user || []
        this.dialog_visible = true
        this.$parent.multiGraphCancellation()
      },
      // 关闭
      close() {
        this.dialog_visible = false
        // 清空
        this.batchPicturesArrTow = []
      },
      // 叉号回调
      crossSign() {
        this.close()
      },
      // 编辑图片
      editMultiGraph(i) {
        this.innerVisible = true
        this.cache = i
      },
      // 内层的打开回调
      innerVisibleshow() {
        this.$nextTick(() => {
          var myCanvas = document.getElementById('myCanvas')
          var Canvas2D = myCanvas.getContext('2d')

          var setw = document.getElementById('getw')
          var seth = document.getElementById('geth')

          console.log('宽高 :>> ', setw.offsetWidth, seth.offsetHeight)

          myCanvas.width = setw.offsetWidth
          myCanvas.height = seth.offsetHeight

          let img = new Image()
          img.src = this.batchPicturesArrTow[this.cache].imgUrl
          img.onload = () => {
            const Atrament = require('atrament')

            const huabi = new Atrament(myCanvas, {
              width: setw.offsetWidth,
              height: seth.offsetHeight,
              color: 'red',
            })

            this.afterEditing = huabi

            Canvas2D.drawImage(img, 0, 0, myCanvas.width, myCanvas.height)
          }
        })
      },
      // 确认编辑
      confirmEdit() {
        this.batchPicturesArrTow[this.cache].imgUrl = this.afterEditing.toImage()
        this.innerVisible = !this.innerVisible
      },
      // 提交
      submit() {
        var checkNum = this.batchPicturesArrTow.length
        var adoptNum = 0
        for (let index = 0; index < this.batchPicturesArrTow.length; index++) {
          this.$refs['item'][index].validate((valid) => {
            if (valid) {
              adoptNum++
            }
          })
        }

        if (adoptNum == checkNum) {
          // 全部通过了
          var Rdata = []
          this.batchPicturesArrTow.forEach(element => {
            element.checkItemIds.push(element.workorder_type)
            Rdata.push({
              // 网点 (现在在等回显)
              pointId: element.pointId,
              // 处理人
              dealWithUserId: element.dealWithUserId,
              // 抄送人
              copyUserId: element.copyUserId,
              // 处理时间
              dealWithTime: element.dealWithTime,
              // 优先级
              priority: element.priority,
              // 备注
              remark: element.remark,
              // 图片类型
              pictureType: 'rectify-before',
              // 图片base64
              base64Picture: element.imgUrl,
              // 通道id和设备id
              workOrderDeviceChannels: element.workOrderDeviceChannels,
              // 问题项id
              checkItemIds: element.checkItemIds,
              imgCreateTime: element.imgCreateTime
            })
          })
          console.log('封装前的请求参数 :>> ', this.batchPicturesArrTow)
          console.log('封装后的请求参数 :>> ', Rdata)

          // 先打开加载条，等到连接完成关闭
          this.fullscreenLoading = true;
          // 添加的请求
          workorderAdd(Rdata)
            .then(res => {
              if (res.code == 0) {
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 4000
                })
                // 关闭加载条和页面
                this.fullscreenLoading = false
                this.close()
              }
            })
            .catch(res => {
              this.$message({
                message: "网络错误",
                type: "error",
              })
            })
        } else {
          // 没有全部通过
          adoptNum = 0
        }

      }
    }
  }
</script>

<style scope>
  .batch {
    display: flex;
  }

  .separationLine {
    width: 100%;
    height: 1px;
    border-top: 1px solid #535252;
    margin-bottom: 30px;
  }

  .buttom {
    display: flex;
    justify-content: center;
  }
</style>
